#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

pthread_mutex_t mutex;    // ding yi yi ba hu chi suo

void *tfn(void *arg)
{
	srand(time(NULL));

	while (1) {
		pthread_mutex_lock(&mutex); // jia suo

		printf("hello ");
		sleep(rand() % 1); // mo ni chang shi jian cao zuo gong xiang zi yuan,dao zhi cpu shi zhong qie huan, chan sheng yu shi jian you guan de cuo wu.
		printf("world\n");

		pthread_mutex_unlock(&mutex);   // jie suo 

		sleep(rand() % 1);
	}
}

int main(int argc, char *argv[]){

	pthread_t tid;
	srand(time(NULL));

	int ret = pthread_mutex_init(&mutex, NULL);
	if (ret != 0)
	{
		fprintf(stderr, "mutex init error: %s\n", strerror(ret));
		exit(1);
	}

	pthread_create(&tid, NULL, tfn, NULL);

	while(1) {
		
		pthread_mutex_lock(&mutex);   // jia suo
		printf("HELLO ");
		sleep(rand() % 1);
		printf("WORLD\n");

		pthread_mutex_unlock(&mutex);   // jie suo

		sleep(rand() % 1);
	}

	phtread_join(tid, NULL);

	pthread_mutex_destroy(&mutex);   // xiao hui hu chi suo
	return 0;
}
